package com.logistic.server.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.logistic.server.common.annotation.LoginRequired;
import com.logistic.server.common.constant.Constants;
import com.logistic.server.common.utils.FileUtils;
import com.logistic.server.entity.common.PageRequest;
import com.logistic.server.entity.common.Result;
import com.logistic.server.entity.common.ResultGenerator;
import com.logistic.server.entity.common.WebUserToken;
import com.logistic.server.entity.pojo.SysRole;
import com.logistic.server.entity.pojo.SysUser;
import com.logistic.server.service.ISysPostService;
import com.logistic.server.service.ISysRoleService;
import com.logistic.server.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户信息 前端控制器
 * </p>
 *
 * @author swen
 * @since 2021-10-26
 */
@Api(value = "用户信息接口", tags = {"用户信息接口"})
@Slf4j
@RestController
@RequestMapping("/system/user")
@LoginRequired
public class SysUserController {

    @Resource
    private ISysUserService userService;

    @Resource
    private ISysRoleService roleService;

    @Resource
    private ISysPostService postService;

    /**
     * 图片本地路径
     */
    @Value("${spring.web.resources.static-locations}")
    private String path;

    /**
    * 用户信息列表
    * @param user 用户信息
    * @param pageRequest 分页参数
    * @return Result
    */
    @ApiOperation(value = "用户信息列表", notes = "用户信息列表")
    @GetMapping
    public Result<?> list(SysUser user, PageRequest pageRequest) {
        return ResultGenerator.genSuccessResult(userService.selectPageUserList(user, pageRequest));
     }

    /**
    * 用户信息新增
    * @param user 用户信息
    * @return Result
    */
    @ApiOperation(value = "用户信息新增", notes = "用户信息新增")
    @PostMapping
    public Result<?> add(@RequestBody SysUser user) {
        userService.insertUser(user);
        return ResultGenerator.genSuccessResult();
    }

    /**
    * 用户信息删除
    * @param ids 用户信息主键
    * @return Result
    */
    @ApiOperation(value = "用户信息删除", notes = "用户信息删除")
    @DeleteMapping("/{ids}")
    public Result<?> delete(@PathVariable String ids) {
        userService.deleteUser(Arrays.asList(ids.split(StringPool.COMMA)));
        return ResultGenerator.genSuccessResult();
    }

    /**
    * 用户信息修改
    * @param user 用户信息
    * @return Result
    */
    @ApiOperation(value = "用户信息修改", notes = "用户信息修改")
    @PutMapping
    public Result<?> update(@RequestBody SysUser user) {
        userService.updateUser(user);
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 根据用户编号获取详细信息
     * @param userId 用户id
     * @return 结果
     */
    @ApiOperation("根据用户编号获取详细信息")
    @GetMapping(value = {"/", "/{userId}"})
    public Result<Map<String, Object>> getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        return ResultGenerator.genSuccessResult(new HashMap<String, Object>() {{
            List<SysRole> roles = roleService.selectRoleAll();
            put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
            put("posts", postService.selectPostAll());
            if (ObjectUtil.isNotNull(userId)) {
                put("user", userService.selectUserById(userId));
                put("postIds", postService.selectPostListByUserId(userId));
                put("roleIds", roleService.selectRoleListByUserId(userId));
            }
        }});
    }

    /**
     * 状态修改
     * @param user 用户
     * @return 结果
     */
    @ApiOperation("状态修改")
    @PutMapping("/changeStatus")
    public Result<?> changeStatus(@RequestBody SysUser user) {
        userService.updateUserStatus(user);
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 根据用户编号获取授权角色
     * @param userId 用户id
     * @return 结果
     */
    @ApiOperation("根据用户编号获取授权角色")
    @GetMapping("/authRole/{userId}")
    public Result<Map<String, Object>> authRole(@PathVariable("userId") Long userId) {
        return ResultGenerator.genSuccessResult(new HashMap<String, Object>() {{
            List<SysRole> roles = roleService.selectRolesByUserId(userId);
            put("user", userService.selectUserById(userId));
            put("roles",SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        }});
    }

    /**
     * 用户授权角色
     * @param userId 用户id
     * @param roleIds 角色id
     * @return 结果
     */
    @ApiOperation("用户授权角色")
    @PutMapping("/authRole")
    public Result<?> insertAuthRole(Long userId, Long[] roleIds) {
        userService.insertUserAuth(userId, roleIds);
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 个人信息
     * @param webUserToken user
     * @return 结果
     */
    @ApiOperation("个人信息")
    @GetMapping("/profile")
    public Result<?> profile(WebUserToken webUserToken) {
        return ResultGenerator.genSuccessResult(new HashMap<String, Object>() {{
            put("user", webUserToken);
            put("roleGroup", userService.selectUserRoleGroup(webUserToken.getUserName()));
            put("postGroup", userService.selectUserPostGroup(webUserToken.getUserName()));
        }});
    }

    /**
     * 修改用户
     * @param user 用户
     * @return 结果
     */
    @ApiOperation( "修改用户")
    @PutMapping("/profile")
    public Result<?> updateProfile(@RequestBody SysUser user) {
        userService.updateProfile(user);
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 重置密码
     */
    @ApiOperation("重置密码")
    @PutMapping("/profile/updatePwd")
    public Result<?> updatePwd(String oldPassword, String newPassword) {
        userService.updatePwd(oldPassword, newPassword);
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 头像上传
     * @param file 文件
     * @return 结果
     * @throws IOException e
     */
    @ApiOperation("用户头像")
    @PostMapping("/profile/avatar")
    public Result<?> avatar(@RequestParam("avatarfile") MultipartFile file, WebUserToken webUserToken) throws Exception {
        if(!file.isEmpty()) {
            if (!Objects.requireNonNull(file.getContentType()).contains("image")) {
                return ResultGenerator.genFailResult("上传文件类型只可以是图片");
            }
            String avatar = Constants.UPLOAD_PATH + FileUtils.uploadFile(file, path);
            userService.updateUserAvatar(avatar);
            return ResultGenerator.genSuccessResult(new HashMap<String, Object>() {{
                put("imgUrl", avatar);
            }});
        }
        return ResultGenerator.genFailResult("上传图片异常，请联系管理员");
    }
}
